import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

Vue.use(VueRouter)

// 路由懒加载
const loadView = (view) => {
  return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
}

const routes = [
  {
    path: '/',
    name: 'Home',
    component: loadView('Home'),
    meta: {
      title: 'home',
      requireAuth: false
    }
  },
  {
    path: '/about',
    name: 'About',
    component: loadView('About'),
    meta: {
      title: 'about',
      requireAuth: false
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: loadView('Login'),
    meta: {
      title: 'login',
      requireAuth: false
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: loadView('Dashboard'),
    meta: {
      title: 'dashboard',
      requireAuth: true
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: loadView('NotFound'),
    meta: {
      title: '404',
      requireAuth: false
    }
  },
  {
    path: '*',
    redirect: '/404'
  },
  {
    path: '/datacenter',
    name: 'datacenter',
    component: loadView('datacenter/datacenter'),
    meta: {
      title: '数据中心',
      requireAuth: false
    }
  },
  {
    path: '/notedata',
    name: 'notedata',
    component: loadView('notedata/notedata'),
    meta: {
      title: '数据中心',
      requireAuth: false
    }
  },
  {
    path: '/test',
    name: 'test',
    component: loadView('test'),
    meta: {
      title: '测试',
      requireAuth: false
    }
  },
]

const router = new VueRouter({
  mode: 'history', // 使用history模式
  base: process.env.BASE_URL,
  routes,
  scrollBehavior: () => ({ y: 0 }) // 切换路由时滚动到顶部
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  // document.title = to.meta.title ? `${to.meta.title} - Vue2 Project` : 'Vue2 Project'
  document.title = to.meta.title

  // 权限验证
  if (to.meta.requireAuth) {
    const token = store.getters['user/token']
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router
